package jiparada;

import java.util.Vector;

import iic2132.INavigator;
import iic2132.World;

public class navigator implements INavigator {

	boolean inicializado = false;
	GSimulatorJiparada sim;//

	Vector<Node> solution;
	char[][] map;
	Node position;
	Node previousPosition;
	PositionJiparada goal;
	int posicionEnPath;

	public WorldJiparada inicializarMapa()
	{
		int tamanoMapa = 150;
		
		int rows = tamanoMapa-1;//buffer.size();
		int cols = tamanoMapa-1;//buffer.get(0).length();

		char mazeData[][] = new char[rows+2][cols+2];
		// init with walls around maze
		for (int i = 0; i < mazeData.length; ++i) {
			for (int j=0; j < mazeData[i].length; ++j) {
				mazeData[i][j] =  WorldJiparada.UNKNOWN;
			}
		}	    

		PositionJiparada startPos = new PositionJiparada(tamanoMapa/2,tamanoMapa/2);
		PositionJiparada goalPos = new PositionJiparada(0,0);

		return new WorldJiparada(mazeData, startPos, goalPos);
	}

	public void inicializar()
	{
		sim = new GSimulatorJiparada(this.inicializarMapa());
		sim.go(1, 1);
		
		goal = new PositionJiparada(-1,-1);
		posicionEnPath=-1;

	}	
	
	public int getDirection(Node now, Node next)
	{
		if(next.x>now.x && next.y==now.y )
			return 0;
		else if(next.x>now.x && next.y<now.y )
			return 1;
		else if(next.x==now.x && next.y<now.y )
			return 2;
		else if(next.x<now.x && next.y<now.y )
			return 3;
		else if(next.x<now.x && next.y==now.y )
			return 4;
		else if(next.x<now.x && next.y>now.y )
			return 5;
		else if(next.x==now.x && next.y>now.y )
			return 6;
		else
			return 7;
			
	}

	public int navigate(char[] surroundings, int direction) {

		if(!inicializado)
		{
			inicializar();
			inicializado= true;
		}
		
		if (surroundings[direction]==World.GOAL) {
			return direction;
		}

		sim.updateGoalPos(direction);
		sim.updateSurroundings(surroundings);
		
		// despues de hacer update de los surroundings, debería tener una posición aproximada del goal.
		position = sim.getRobotPosition();
		map = sim.getMapData();
		PositionJiparada newGoal = sim.getGoalPos();
		newGoal.x=newGoal.col;
		newGoal.y=newGoal.row;
		
		//if(!newGoal.equals(goal) || posicionEnPath<0)
		//if(posicionEnPath<0 || surroundings[getDirection(position,solution.get(posicionEnPath))]==World.OBSTACLE)
		{
			goal.x = newGoal.x;
			goal.y = newGoal.y;
			solution = PathSolver.search((Node)position,goal,map);
			while(solution == null)
			{
				solution = PathSolver.search((Node)position,goal,map);
			}
			posicionEnPath=solution.size()-2;
			
			if(previousPosition!=null)
			PathSolver.setVisited(previousPosition);
			
			previousPosition = solution.get(posicionEnPath);
		}
		
		
		int newDirection = getDirection(position,solution.get(posicionEnPath));
		posicionEnPath--;
		sim.updateRobotPosition(newDirection);
		return newDirection;

	}

}
